package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.comment.service.CommentRepayService;
import com.heima.commom.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojo.ApComment;
import com.heima.model.comment.pojo.ApCommentRepay;
import com.heima.model.comment.pojo.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojo.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by jojo
 * @Date 2022/3/10
 * @Description
 */
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 分布式锁
     */
    @Autowired
    private RedissonClient client;
    /**
     * 保存评论回复信息
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
//        1. 校验参数
//                校验是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"回复评论需要登录后操作");
        }
//        校验评论id  校验内容不为空  校验内容长度不能大于140个字符 (validated校验)
//        2. 阿里云校验评论内容是否违规
//                (简单:  此步不做      普通: 阿里云检测有问题提示      高级:  有问题不报异常，替换为**)
//        3. 远程查询当前登陆用户信息
        RLock replyLock = client.getLock("reply-lock");
        try {
            replyLock.lock();
            ResponseResult<ApUser> userById = userFeign.findUserById(apUser.getId());
            if (!userById.checkCode()) {
                log.error("远程查询当前登陆用户信息失败");
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
            }
            ApUser user = userById.getData();
            //判断该评论是否存在
            Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
            ApComment one = mongoTemplate.findOne(query, ApComment.class);
            if (one==null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该评论不存在");
            }
//        4. 创建回复评论信息，并保存到mongo
            ApCommentRepay apCommentRepay = new ApCommentRepay();
            apCommentRepay.setCommentId(dto.getCommentId());
            apCommentRepay.setContent(dto.getContent());
            apCommentRepay.setAuthorId(user.getId());
            apCommentRepay.setAuthorName(user.getName());
            apCommentRepay.setLikes(0);
            apCommentRepay.setCreatedTime(new Date());
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.save(apCommentRepay);
            //5.给评论信息回复数加1
            Integer reply = one.getReply();
            Integer i=1;
            Update update = new Update();
            update.set("reply",reply+i);
            mongoTemplate.updateMulti(query,update, ApComment.class);
        } finally {
            replyLock.unlock();
        }
        return ResponseResult.okResult();
    }

    /**
     * 保存评论回复点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likeCommentRepay(CommentRepayLikeDTO dto) {
//        1. 参数校验
//        评论回复id不能为空  operation必须为 0  或  1
//        2. 根据评论回复id查询评论回复数据， 为null返回错误信息
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        String commentRepayId = dto.getCommentRepayId();
        RLock rLock = client.getLock("repayLike-lock");

        try {
            rLock.lock();
            Query query = Query.query(Criteria.where("id").is(commentRepayId));
            ApCommentRepay one = mongoTemplate.findOne(query, ApCommentRepay.class);
            if (one==null) {
                log.error("评论回复不存在");
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"评论回复不存在");
            }
//        3. 如果是点赞操作 判断是否已经点赞
            Short operation = dto.getOperation();
            Integer userId = apUser.getId();
            Integer likes = one.getLikes();
            Integer i=1;
            Update update = new Update();
            Map map= new HashMap<>();
            if (operation.equals((short)0)) {
                query=Query.query(Criteria.where("commentRepayId").is(commentRepayId).and("authorId").is(userId));
                ApCommentRepayLike likeOne = mongoTemplate.findOne(query, ApCommentRepayLike.class);
                if (likeOne!=null) {
                    // 点过赞提示 请勿重复点赞
                    CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
                }
    //        未点过赞   保存点赞信息到mongo
                ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
                apCommentRepayLike.setCommentRepayId(commentRepayId);
                apCommentRepayLike.setAuthorId(userId);
                mongoTemplate.save(apCommentRepayLike);
    //        并修改评论信息的点赞数量( + 1)
                query=Query.query(Criteria.where("id").is(commentRepayId));
                update.set("likes",likes+i);
                mongoTemplate.updateMulti(query,update,ApCommentRepay.class);
                //查修改之后的评论信息
                ApCommentRepay repayOne = mongoTemplate.findOne(query, ApCommentRepay.class);
                assert repayOne != null;
                map.put("likes",repayOne.getLikes());
                return ResponseResult.okResult(map);
            }else {
                query=Query.query(Criteria.where("id").is(commentRepayId));
                ApCommentRepay one1 = mongoTemplate.findOne(query, ApCommentRepay.class);
                if (one1!=null&&one1.getLikes()<=0) {
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"取消点赞数量不能为负数！！！");
                }
    //        4. 如果是取消点赞操作
    //                删除点赞信息
                query=Query.query(Criteria.where("commentRepayId").is(commentRepayId).and("authorId").is(userId));
                mongoTemplate.remove(query,ApCommentRepayLike.class);
    //        并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
                update.set("likes",likes<=0?0:likes - i);
                query=Query.query(Criteria.where("id").is(commentRepayId));
                mongoTemplate.updateMulti(query,update,ApCommentRepay.class);
                //  5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
                //查修改之后的评论信息
                ApCommentRepay repayOne = mongoTemplate.findOne(query, ApCommentRepay.class);
                assert repayOne != null;
                map.put("likes",repayOne.getLikes());
                return ResponseResult.okResult(map);
            }
        } finally {
            rLock.unlock();
        }
    }
    /**
     * 加载评论回复列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
//        1. 参数校验
//                校验文章id

        String commentId = dto.getCommentId();
        Date minDate = dto.getMinDate();
//        校验size
        if (dto.getSize()==null) {
            dto.setSize(10);
        }
//        2. 根据条件查询评论回复列表
//                (评论id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
        Query query = Query.query(Criteria.where("commentId").is(commentId).and("createdTime").lt(minDate));
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        query.limit(dto.getSize());
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
//        3. 判断当前用户是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser==null) {
            //        4. 如果未登录直接返回评论列表

            return ResponseResult.okResult(apCommentRepays);
        }else {
            //        5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
//                (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
//        推荐实现:
//        5.1 根据当前列表中评论回复id  和  登录人id 查询评论点赞表，得到点赞数据
//        commentId  in    评论id列表   authorId = 登录人id
            List<String> commentRepayIds = apCommentRepays.stream()
                    .map(ApCommentRepay::getId)
                    .collect(Collectors.toList());
            query=Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentRepayId").in(commentRepayIds));
            List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query, ApCommentRepayLike.class);
//        5.2 遍历评论列表
//        将每一个评论  ApCommentRepay 转成 ApCommentRepayVO
            ApCommentRepayVO vo = null;
            ArrayList<ApCommentRepayVO> listVos = new ArrayList<>();
            for (ApCommentRepay apCommentRepay : apCommentRepays) {
                 vo = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay,vo);
                // 其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
                if (CollectionUtils.isNotEmpty(apCommentRepayLikes)) {
                    vo.setOperation((short)0);
                }
                listVos.add(vo);
            }
            return ResponseResult.okResult(listVos);
        }
    }
}
